﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Willow.IRepository;
using Willow.IService;
using Willow.Model;
using Willow.Extensions;
using Willow.IService.Auth;
namespace Willow.Service.Auth
{
    public class RoleService : BaseService<Auth_Role>, IRoleService
    {

        IRepository<Auth_UserRole> UserRoleRepository;

        public RoleService(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
            UserRoleRepository = unitOfWork.GetStandardRepository<Auth_UserRole>();
        }

        /// <summary>
        /// 提交角色
        /// </summary>
        /// <param name="lstInsert">The LST insert.</param>
        /// <param name="lstDelete">The LST delete.</param>
        /// <param name="lstUpdate">The LST update.</param>
        public void Submit(IEnumerable<Auth_Role> lstInsert, IEnumerable<Auth_Role> lstDelete, IEnumerable<Auth_Role> lstUpdate)
        {

            foreach (var item in lstInsert.OrEmptyIfNull())
            {
                item.Id = Guid.NewGuid();
                item.IsDelete = false;
                base.Create(item);
            }

            foreach (var item in lstDelete.OrEmptyIfNull())
            {
                var obj = base.Find(item.Id);
                obj.IsDelete = true;
                base.Update(obj);
            }

            foreach (var item in lstUpdate.OrEmptyIfNull())
            {
                base.Update(item);
            }

            UnitOfWork.SaveChanges();
        }

        /// <summary>
        /// 分配角色
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="roleIds">The role ids.</param>
        public void DistributeRole(Guid userId, Guid[] roleIds)
        {
            var lstUserModule = UserRoleRepository.Filter(p => p.UserId == userId).ToList();
            foreach (var item in lstUserModule)
            {
                UserRoleRepository.Delete(item);
            }

            foreach (var roleId in roleIds.OrEmptyIfNull())
            {
                var roleModule = new Auth_UserRole
                {
                    Id = Guid.NewGuid(),
                    UserId = userId,
                    RoleId = roleId
                };
                UserRoleRepository.Create(roleModule);
            }

            UnitOfWork.SaveChanges();
        }
    }
}
